package logic

import (
	"2211a_mayi/service/models"
	"2211a_mayi/service/pkg"
	"context"
	"errors"
	"github.com/google/uuid"
	"strconv"

	"2211a_mayi/service/internal/svc"
	"2211a_mayi/service/mayi"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *mayi.CreateOrderRequest) (*mayi.CreateOrderResponse, error) {
	// 商品是否存在
	var g models.Goods
	var err error
	err = g.Detail(int(in.GoodsId))
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	// 库存是否充足
	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	var order models.Order
	order.UserId = int(in.UserId)
	order.OrderSn = uuid.NewString()
	order.Amount = float64(in.Num) * g.GoodsPrice

	err = order.Create()
	if err != nil {
		logx.Error(err)
		return nil, err
	}

	var orderGoods models.OrderGoods
	orderGoods.OrderId = int(order.ID)
	orderGoods.GoodsId = int(in.GoodsId)
	orderGoods.GoodsTitle = g.GoodsTitle
	orderGoods.GoodsCover = g.GoodsCover
	orderGoods.GoodsPrice = g.GoodsPrice
	orderGoods.GoodsNum = int(in.Num)

	err = orderGoods.Create()
	if err != nil {
		logx.Error(err)
		return nil, err
	}

	// 减少库存
	g.GoodsStock -= int(in.Num)
	err = g.Update()
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	amount := strconv.FormatFloat(order.Amount, 'f', 2, 64)
	// 支付宝支付
	url := pkg.Pay(order.OrderSn, amount)

	return &mayi.CreateOrderResponse{
		PayUrl: url,
	}, nil
}
